﻿using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SHKF.B2C.MeiTuanShanGou.BLL;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.Medicine;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.Token;
using SHKF.B2C.MeiTuanShanGou.Model.Entity.Medicine;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Dto.Center;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Req;
using SkyApm;
using SkyApm.Tracing;
using SkyApm.Tracing.Segments;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SHKF.B2C.MeiTuanShanGou.Service.Controllers
{
    [Route("[controller]")]
    public class NonProductController : Base2Controller
    {
        private readonly ProductInfoMapBLL productInfoMapBLL;
        private readonly ShopMapBLL shopMapBLL;

        public NonProductController(
            ProductInfoMapBLL productInfoMapBLL,
            ShopMapBLL shopMapBLL,
            IServiceProvider serviceProvider,
            ILogger<NonProductController> logger) : base(serviceProvider, logger)
        {
            this.productInfoMapBLL = productInfoMapBLL;
            this.shopMapBLL = shopMapBLL;
        }

        #region 上传产品信息到美团

        [NonAction]
        [CapSubscribe("SHKF.B2C.Mtsg.Product.Save", Group = "SHKF.B2C.Mtsg.Product")]
        public async Task<IActionResult> Save(ProductInfo productInfo, [FromCap] CapHeader header)
        {

            //从Erp向平台 
            try
            {
                Console.WriteLine($"mtsg:{productInfo.Upc}");

                string msg = "";

                base.AddLog("2.0 cap mtsg save start");

                List<string> values = new List<string>();

                //upc
                if (string.IsNullOrEmpty(productInfo.Upc))
                {
                    throw new Exception("药品UPC码不能为空");
                }

                string json = JsonConvert.SerializeObject(productInfo);
                base.AddLog($"2.1 => mtsg.start json:{json}");

                long ShopSN = productInfo.ShopSN;

                List<ShopMapEntity> shops = this.shopMapBLL.Query(ShopSN, PlatformEnum.Mtsg);
                if (shops == null || shops.Count == 0)
                {
                    msg += $"请在B2C平台创建虚拟商店 {productInfo.ShopSN}";
                }
                if (msg != "")
                {
                    throw new Exception(msg);
                }

                //上架成功！
                DataDto dtoMtsg = await this.SaveMtsg(productInfo, shops[0]);
                if (dtoMtsg.error != null)
                {
                    msg += $"虚拟店铺{ShopSN}" + dtoMtsg.error.msg;
                }
                else
                {
                    base.AddLog($"2.3 => mtsg.end: Upc:{productInfo.Upc}; app_medicine_code:{productInfo.ID}");
                }

                if (msg != "")
                {
                    throw new Exception(msg);
                }

                base.AddLog("2.4 cap mtsg save end");

                base.Release();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                base.Release();
            }

            return Ok();
        }

        private async Task<DataDto> SaveMtsg(ProductInfo product, ShopMapEntity shop)
        {
            DataDto dto = new DataDto();

            string CategoryName = "";
            string msg = this.CheckMtsg(product, shop, out CategoryName);

            if (msg != "")
            {
                dto.error = new Error() { code = -1, msg = msg };
                return dto;
            }
            long app_poi_code = shop.app_poi_code;
            product.ShopSN = app_poi_code;

            //上传美团
            TokenMeiTuanDto token = await this.GetMtsgToken(app_poi_code);
            if (token.error != null)
            {
                dto.error = new Error() { code = token.status, msg = token.error.msg };
                return dto;
            }

            this.httpClientMeiTuanShanGou.GetTimeStamp();

            //向美团上传
            string CategoryCode = "";
            await SendMtsg(product, app_poi_code, CategoryCode, CategoryName);
            //}

            return dto;
        }

        private async Task<DataDto> SendMtsg(ProductInfo product, long app_poi_code, string CategoryCode, string CategoryName)
        {
            MedicineInfo medicine = new MedicineInfo();
            medicine.app_medicine_code = product.ID;
            medicine.app_poi_code = app_poi_code;
            medicine.category_code = CategoryCode;
            medicine.category_name = CategoryName;
            //medicine.ctime = DateTimeUtil.DateTimeToTimeStamp(DateTime.Now);
            medicine.is_sold_out = 1;
            medicine.medicine_no = product.LiceseId;
            medicine.medicine_type = 1;
            medicine.name = product.ProductName;
            medicine.price = (float)product.Price;
            medicine.sequence = 0;
            medicine.spec = product.Spec;
            medicine.stock = product.Stock.ToString();
            medicine.upc = product.Upc;
            //medicine.utime = DateTimeUtil.DateTimeToTimeStamp(DateTime.Now);

            DataDto dto = new DataDto();

            DataDto dataDto = await this.httpClientMeiTuanShanGou.MedicineSave(medicine);
            Error error = dataDto.error;
            if (error != null)
            {
                //3008: 已经存在    901:Upc 已经存在   
                dto.error = error;
                if (error.code == 3008 || error.code == 901)
                {
                    //存在只上架
                    dataDto = await PostIsSoldOut(app_poi_code, product.ID);

                    base.AddLog($"2.2 => 3008:901 app_poi_code.{app_poi_code}; ID:{product.ID} 已经存在，强制上架成功!");
                    if (dataDto.error != null)
                    {
                        error.msg += " " + dataDto.error.msg;
                    }
                }
            }
            else
            {
                base.AddLog($"2.2 => Upc:{product.Upc} 美团上传成功!");
                if (dataDto.data == "ok")
                {
                    //保存到map中
                    //ProductInfoMapEntity map = new ProductInfoMapEntity();
                    //map.Platform = PlatformEnum.Mtsg;
                    //map.Upc = product.Upc;
                    //map.app_medicine_code = product.ID;
                    //map.pDate = DateTime.Now;
                    //map.FKSN = product.SN;
                    //this.productInfoBLL.MapSave(map);

                    base.AddLog($"2.2 => Upc:{product.Upc} map产品映射表保存成功!");
                }
                else
                {
                    base.WriteInformation("SaveMtsg>data", dto.data);
                }
            }

            return dto;
        }

        private string CheckMtsg(ProductInfo product, ShopMapEntity shop, out string CategoryName)
        {
            string msg = "";

            //price
            int scale = 0; //小数位数
            decimal price = product.Price;

            string[] parr = price.ToString().Split('.');

            if (parr.Length > 1)
            {
                scale = parr[1].Length;
            }
            if (scale > 2 || price < 0 || price > (Decimal)30000.00)
            {
                msg += "最多支持2位小数，不能为负数，最大支持30000.00";
            }

            //stock
            //int stock = product.Stock;
            //if (stock < 0 || stock > 99999)
            //{
            //    msg += "不能为负数或小数，最大允许99999";
            //}

            //category_code
            CategoryName = "";
            if (string.IsNullOrEmpty(CategoryName) && shop != null)
            {
                CategoryName = shop.CategoryName;
            }

            if (string.IsNullOrEmpty(CategoryName))
            {
                msg += "分类名称不能为空";
            }

            return msg;
        }

        private async Task<DataDto> PostIsSoldOut(long app_poi_code, string ID)
        {
            DataDto dto = new DataDto();
            IsSoldOutDto isSoldOutDto = new IsSoldOutDto();
            isSoldOutDto.app_poi_code = app_poi_code;

            List<MedicineData> medicineDatas = new List<MedicineData>();
            medicineDatas.Add(
                new MedicineData() { app_medicine_code = ID, is_sold_out = 0 }
          );
            isSoldOutDto.medicine_data = medicineDatas;
            dto = await this.httpClientMeiTuanShanGou.PostIsSoldOut(isSoldOutDto);

            return dto;
        }

        #endregion

        #region 更新库存

        [NonAction]
        [CapSubscribe("SHKF.B2C.Mtsg.Product.Stock", Group = "SHKF.B2C.Mtsg.Product")]
        public async Task<IActionResult> Stock(StockInfo data, [FromCap] CapHeader header)
        {
            try
            {
                base.AddLog("2.0 cap mtsg stock start");

                string msg = "";
                List<ShopMapEntity> shops = this.shopMapBLL.Query(data.ShopSN, PlatformEnum.Mtsg);
                if (shops == null || shops.Count == 0)
                {
                    msg += $"请在B2C平台创建虚拟商店 {data.ShopSN}";
                }
                if (msg != "")
                {
                    throw new Exception(msg);
                }

                ProductStock prodcutStock = new ProductStock();
                prodcutStock.app_poi_code = shops[0].app_poi_code; //店铺sn

                bool bOk = true;

                List<StockQty> medicine_data = new List<StockQty>();
                foreach (var item in data.Items)
                {
                    StockQty stock = new StockQty();
                    stock.stock = item.Qty;

                    //查询映射到美团的产品ID
                    string app_medicine_code = this.productInfoMapBLL.QueryMedicineCode(data.ShopSN, item.Upc, PlatformEnum.Mtsg);
                    if (app_medicine_code == "")
                    {
                        msg += $"ShopSN:{data.ShopSN} Upc:{item.Upc} Mtsg不存在映射";
                        bOk = false;
                        break;
                    }

                    stock.app_medicine_code = app_medicine_code;
                    stock.app_poi_code = prodcutStock.app_poi_code;

                    medicine_data.Add(stock);
                }
                prodcutStock.medicine_data = medicine_data;

                if (bOk)
                {
                    TokenMeiTuanDto token = await this.GetMtsgToken(prodcutStock.app_poi_code);
                    if (token.error != null)
                    {
                        msg += token.error.msg;
                        throw new Exception(msg);
                    }

                    this.httpClientMeiTuanShanGou.GetTimeStamp();

                    DataDto dto = await this.httpClientMeiTuanShanGou.Stock(prodcutStock);
                    if (dto.error != null)
                    {
                        throw new Exception(dto.error.msg);
                    }

                    base.AddLog("2.1 cap mtsg stock end");
                }
                else
                {
                    throw new Exception(msg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                base.Release();
            }

            return Ok();
        }

        #endregion

        #region 更新价格

        [NonAction]
        [CapSubscribe("SHKF.B2C.Mtsg.Product.Price", Group = "SHKF.B2C.Mtsg.Product")]
        public async Task<IActionResult> Price(StockInfo data, [FromCap] CapHeader header)
        {
            try
            {
                base.AddLog("2.0 cap mtsg stock start");

                string msg = "";

                List<ShopMapEntity> shops = this.shopMapBLL.Query(data.ShopSN, PlatformEnum.Mtsg);
                if (shops == null)
                {
                    msg += $"{data.ShopSN}没有配置美团闪购SN";
                }

                if (msg != "")
                {
                    throw new Exception(msg);
                }

                long app_poi_code = shops[0].app_poi_code;

                MedicinePrice medicinePrice = new MedicinePrice();
                medicinePrice.app_poi_code = app_poi_code.ToString();

                List<MedicinePriceData> list = new List<MedicinePriceData>();
                medicinePrice.medicine_data = list;

                foreach (var item in data.Items)
                {
                    MedicinePriceData dataPrice = new MedicinePriceData();
                    dataPrice.price = item.Price;

                    string app_medicine_code = this.productInfoMapBLL.QueryMedicineCode(data.ShopSN, item.Upc, PlatformEnum.Mtsg);
                    if (app_medicine_code == "")
                    {
                        msg += $"ShopSN:{data.ShopSN} Upc:{item.Upc} Mtsg不存在映射";
                    }

                    dataPrice.app_medicine_code = app_medicine_code;
                    list.Add(dataPrice);
                }

                if (msg != "")
                {
                    throw new Exception(msg);
                }


                httpClientMeiTuanShanGou.GetTimeStamp();

                TokenMeiTuanDto token = await this.GetMtsgToken(app_poi_code);
                if (token.status != 0)
                {
                    msg += token.message;
                }

                if (msg != "")
                {
                    throw new Exception(msg);
                }

                MedicinePriceDto dto = await httpClientMeiTuanShanGou.BatchUpdatePrice(medicinePrice);
                if (dto.error != null)
                {
                    throw new Exception(dto.error.msg);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                base.Release();
            }

            return Ok();
        }

        #endregion

    }
}
